package com.qf.common.core.thread;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class ThreadPoolConfig {

    /**
     * 自定义的线程池对象
     * @return
     */
    @Bean
    @Primary
    public Executor getExecutors(){
        //获取CPU核心数
        Runtime runtime = Runtime.getRuntime();
        int core = runtime.availableProcessors();//获取cpu的核心数
        System.out.println("当前电脑的cpu核心数：" + core);

        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        //线程池的核心线程数 - 线程池初始化后里面的线程数 （推荐设置cpu的核心数）
        taskExecutor.setCorePoolSize(core);
        //设置最大线程
        taskExecutor.setMaxPoolSize(core * 2);
        //线程池中阻塞队列的大小
        taskExecutor.setQueueCapacity(10000);
        //设置线程的拒绝策略
        /**
         * CallerRunsPolicy - 如果阻塞队列已满，则使用当前线程执行该任务
         * AbortPolicy - 直接丢弃任务
         * DiscardPolicy - 抛出异常
         * DiscardOldestPolicy - 丢弃阻塞队列中最老的任务
         */
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //设置线程的空闲时间 - 超出核心线程数的线程
        taskExecutor.setKeepAliveSeconds(60);
        //线程池中线程名称的固定前缀
        taskExecutor.setThreadNamePrefix("ken-thread-");
        //初始化线程池
        taskExecutor.initialize();
        //返回线程池
        return taskExecutor;
    }
}
